import router from './index';
import { getToken } from '@/utils/cookies'; // get token from cookie
import { useUserStore } from '@/store/modules/user';
import { usePermissionStore } from '@/store/modules/permission';

let LoadingBar;
const whiteList = ['/login', '/licence']; // no redirect whitelist

router.beforeEach(async (to, from, next) => {
	const userStore = useUserStore();
	LoadingBar = window['$loadingBar'];
	// const Message = window['$message'];
	LoadingBar.start();

	const hasToken = getToken();
	if (hasToken) {
		if (userStore.allRoles.length > 0) {
			if (to.path === '/login') {
				next({ path: '/' });
			} else {
				next();
			}
		} else {
			const { allRoles } = await userStore.getUserAuthorize();
			// 获取路由
			const permissionStore = usePermissionStore();
			const routes = await permissionStore.generateRoutes(allRoles);
			routes.map(item => {
				router.addRoute(item);
			});
			next({ ...to, replace: true });
		}
		LoadingBar.finish();
	} else {
		if (whiteList.indexOf(to.path) !== -1) {
			next();
		} else {
			next(`/login?redirect=${to.path}`);
			LoadingBar.finish();
		}
	}
});

router.afterEach(() => {
	LoadingBar.finish();
});
